package com.corecmd.tcloud.tcimserver.controller;

import com.corecmd.tcloud.tcimserver.domain.UserInfoDO;
import com.corecmd.tcloud.tcimserver.enums.AvailableStatusEnum;
import com.corecmd.tcloud.tcimserver.enums.GenderEnum;
import com.corecmd.tcloud.tcimserver.enums.LoginTypeEnum;
import com.corecmd.tcloud.tcimserver.service.IUserService;
import com.corecmd.tcloud.tcimserver.shiro.CustomUsernamePasswordToken;
import com.corecmd.tcloud.tcimserver.utils.CustomResponse;
import com.corecmd.tcloud.tcimserver.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/25
 * @description :
 **/
@Api(tags = "登录授权API")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "/login")
public class LoginController {
    @Value("${imserver.host}")
    private String imHost;
    @Value("${imserver.port}")
    private String imPort;
    @Autowired
    private IUserService userService;

    @ApiOperation(value = "im登陆")
    @RequestMapping(value = "/imLogin",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "userId",value = "登录账号|邮箱|手机号",dataType = "int",required = true),
            @ApiImplicitParam(paramType = "query",name = "password",value = "密码",dataType = "String",required = true)
    })
    public CustomResponse imLogin(@RequestParam int userId, @RequestParam String password){
        CustomResponse customResponse = null;
        log.info("用户：{}登录im",userId);
        CustomUsernamePasswordToken usernamePasswordToken = new CustomUsernamePasswordToken(String.valueOf(userId),password, LoginTypeEnum.PASSWORD,null);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            //登录成功后，需要返回登录的token
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("loginRoleId","");
            customResponse = CustomResponse.ok();
            customResponse.put("message","Im身份认证成功");
            customResponse.put("imHost",imHost);
            customResponse.put("imPort",imPort);
            customResponse.put("authToken",session.getId().toString());
        } catch (LockedAccountException e) {
            customResponse = CustomResponse.error("账号已被锁定,请联系管理员");
        } catch (Exception e) {
            customResponse = CustomResponse.error("账号或密码错误");
        }
        return customResponse;
    }

    @ApiOperation("注册新用户")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    private CustomResponse register(@RequestParam String userName,@RequestParam String password,@RequestParam String email){
        CustomResponse customResponse = new CustomResponse();
        try {
            UserInfoDO newUser = new UserInfoDO();
            newUser.setCreateTime(new Date());
            newUser.setEmail(email);
            newUser.setPassword(MD5Utils.encrypt(password));
            newUser.setUserName(userName);
            newUser.setUserType('0');
            newUser.setGender(GenderEnum.UNKNOWN.getGender());
            newUser.setStatus(AvailableStatusEnum.YES.getCode());
            int result = userService.regist(newUser);
            customResponse = result>0?CustomResponse.ok("注册成功"):CustomResponse.error("注册失败");
        } catch (Exception e) {
            log.info("注册用户异常",e);
            customResponse = CustomResponse.error("注册用户失败");
        }
        return customResponse;
    }

    @ApiIgnore
    @RequestMapping(value = "/needLogin")
    public CustomResponse needLogin(){
        return CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"请先登录获取授权");
    }

}
